<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExportExcel">excel导出</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" :default-sort="{prop:'workNumber',order:'ascending'}">
          <!-- <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto">
            </template>
          </el-table-column> -->
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment)||'未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="账户状态">
            <template #default="{row}">
              {{ row.enableState }}
              <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <paging :total="total" :page="page" :pagesize="size" @SizeChange="SizeChange" @CurrentChange="CurrentChange" />
        </el-row>
      </el-card>
      <!-- 新增 -->
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @closed="reset"
      >
        <employees-dialog
          ref="formDialog"
          @close="showDialog=false"
          @load="loadAddEmployees"
        />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role
          :id="id"
          ref="assignRoleRef"
          @close="showDialogRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeesAllList, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import employeesDialog from './employeesDialog.vue'
import AssignRole from './assignRole.vue'
// const hireType = {}
//  [{id: 1,value: '正式'},{id: 2,value: '非正式'}]===>>{1:'正式',2:'非正式'}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: { employeesDialog, AssignRole },
  data() {
    return {
      page: 1,
      size: 5,
      total: 0,
      employeesList: [],
      value: true,
      showDialog: false, // 控制新增显示与隐藏
      showDialogRole: false, // 控制分配角色的显示与隐藏
      id: ''
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    // 分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.id = id
      this.$nextTick(() => {
        this.$refs.assignRoleRef.loadSetRoleList()
      })
    },
    // 导出
    async hExportExcel() {
      try {
        const res = await getEmployeesAllList({ page: this.page, size: this.size })
        console.log('hExportExcel', res)
        const list = res.data.rows
        const { header, data } = this.formatData(list)
        console.log(header, data)
        // import('@/vendor/Export2Excel').then(excel => {
        //   // excel表示导入的模块对象
        //   console.log(excel)
        //   excel.export_json_to_excel({
        //     header: ['姓名', '工资'], // 表头 必填
        //     data: [
        //       ['刘备', 100],
        //       ['关羽', 500]
        //     ], // 具体数据 必填
        //     filename: 'excel-list', // 文件名称
        //     autoWidth: true, // 宽度是否自适应
        //     bookType: 'xlsx' // 生成的文件类型
        //   })
        // })
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header,
            data,
            filename: '实例',
            autoWidth: true,
            bookType: 'xlsx'
          })
        })
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化函数
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址',
        'enableState': '状态'
      }
      let header = []
      let data = []
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(enKey => map[enKey])
      data = list.map(obj => {
        obj.formOfEmployment = hireType[obj.formOfEmployment] || '未知'
        return Object.values(obj)
      })
      return { header, data }
    },
    // 重置表单
    reset() {
      this.$refs.formDialog.resetForm()
    },
    // 增加员工分页跳到最后一页
    loadAddEmployees() {
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeesList()
    },
    // 删除
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log(res)
        this.$message.success(res.message)
        if (this.employeesList.length === 1) {
          this.page--
          if (this.page <= 1) {
            this.page = 1
          }
        }
        this.loadEmployeesList()
        // 保存数据
      } catch (err) {
        console.log(err)
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确定
        this.doDel(id)
      }).catch(() => {
      //  取消
      })
    },
    // 聘用形式函数
    formOfEmploymentFormat(id) {
      // const obj = EmployeesEnum.hireType.find(item => item.id === id)
      // console.log(obj)
      // if (obj) {
      //   return obj.value
      // } else {
      //   return '未知'
      // }
      return hireType[id]
    },
    // 分页
    SizeChange(val) {
      this.size = val
      this.page = 1
      this.loadEmployeesList()
    },
    CurrentChange(val) {
      this.page = val
      this.loadEmployeesList()
    },
    // 加载员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeesAllList({ page: this.page, size: this.size })
        console.log(res)
        this.total = res.data.total
        this.employeesList = res.data.rows
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>
